#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
int ticket = 1000;
pthread_mutex_t mutex;
void* route(void* arg){
  int id = (int)arg;
  while(1){
    pthread_mutex_lock(&mutex);
    if(ticket > 0){
      usleep(1000);
      printf("thread:%d sells ticket:%d\n",id,ticket);
      ticket--;
      pthread_mutex_unlock(&mutex);
    }
    else {
      pthread_mutex_unlock(&mutex);
      break;
    }
  }
}


int main()
{
 
  pthread_t tid[4];
  pthread_mutex_init(&mutex,NULL);
  int i = 0;
  for(;i < 4;++i){
    pthread_create(tid+i,NULL,route,(void*)i);
  }
 
  for(i = 0;i < 4;++i){
    pthread_join(tid[i],NULL);
  }
  pthread_mutex_destroy(&mutex);
  return 0;
}
